/**
 * 需求相关的工具函数
 * 用于新建和详情页面的共享逻辑
 */
import { nextTick } from 'vue'
import type { Ref } from 'vue'
import { useRequirementStates } from '@/composables/useRequirementStates'
import { useRequirementOptions } from '@/composables/useRequirementOptions'
import type { RequirementType } from '@/api/requirements'

export interface StatusOption {
  value: string
  label: string
  color?: string
}

export interface BasicOption {
  value: string
  label: string
  color?: string
}

export interface ProjectOption {
  id: string
  name: string
}

export interface UserOption {
  id: string
  name: string
}

export interface VersionOption {
  id: string
  name: string
  version_number?: string
  status?: string
  project_id?: string
  projectName?: string
}

/**
 * 获取状态类型（用于 Element Plus tag）
 */
export function getStatusType(status: string, statusOptions: StatusOption[]): 'info' | 'success' | 'warning' | 'danger' {
  const { getStatusType: getStatusTypeFromComposable } = useRequirementStates()
  // 优先使用 composable 中的函数
  try {
    return getStatusTypeFromComposable(status) as 'info' | 'success' | 'warning' | 'danger'
  } catch {
    // 如果 composable 不可用，使用选项中的颜色
    const option = statusOptions.find(item => item.value === status)
    if (!option?.color) return 'info'
    const colorMap: Record<string, 'info' | 'success' | 'warning' | 'danger'> = {
      '#909399': 'info',
      '#409EFF': 'info',
      '#67C23A': 'success',
      '#E6A23C': 'warning',
      '#F56C6C': 'danger'
    }
    return colorMap[option.color] ?? 'info'
  }
}

/**
 * 获取状态文本
 */
export function getStatusText(status: string, statusOptions: StatusOption[]): string {
  const { getStatusName } = useRequirementStates()
  // 优先使用 composable 中的函数
  try {
    return getStatusName(status)
  } catch {
    // 如果 composable 不可用，使用选项中的标签
    const option = statusOptions.find(item => item.value === status)
    return option?.label || status
  }
}

/**
 * 获取优先级类型（用于 Element Plus tag）
 */
export function getPriorityType(priority: string, priorityOptions: BasicOption[]): 'info' | 'success' | 'warning' | 'danger' {
  const { getPriorityType: getPriorityTypeFromComposable } = useRequirementOptions()
  // 优先使用 composable 中的函数
  try {
    return getPriorityTypeFromComposable(priority) as 'info' | 'success' | 'warning' | 'danger'
  } catch {
    // 如果 composable 不可用，使用选项中的颜色
    const option = priorityOptions.find(item => item.value === priority)
    if (!option?.color) return 'info'
    const colorMap: Record<string, 'info' | 'success' | 'warning' | 'danger'> = {
      '#909399': 'info',
      '#409EFF': 'info',
      '#67C23A': 'success',
      '#E6A23C': 'warning',
      '#F56C6C': 'danger'
    }
    return colorMap[option.color] ?? 'info'
  }
}

/**
 * 获取优先级文本
 */
export function getPriorityText(priority: string, priorityOptions: BasicOption[]): string {
  const { getPriorityName } = useRequirementOptions()
  // 优先使用 composable 中的函数
  try {
    return getPriorityName(priority)
  } catch {
    // 如果 composable 不可用，使用选项中的标签
    const option = priorityOptions.find(item => item.value === priority)
    return option?.label || priority
  }
}

/**
 * 获取类型文本
 */
export function getTypeText(type: string | RequirementType): string {
  const { getTypeName } = useRequirementOptions()
  // 使用 composable 中的函数
  return getTypeName(String(type))
}

/**
 * 获取来源文本
 */
export function getSourceText(source: string): string {
  const { getSourceName } = useRequirementOptions()
  // 使用 composable 中的函数
  return getSourceName(source)
}

/**
 * 获取版本选项标签
 */
export function getVersionOptionLabel(option: VersionOption): string {
  if (!option) return ''
  const numberPart =
    option.version_number && option.version_number !== option.name ? `${option.version_number} - ` : ''
  const projectPart = option.projectName ? `（${option.projectName}）` : ''
  return `${numberPart}${option.name}${projectPart}`
}

/**
 * 清除字段错误
 */
export function clearFieldError(field: string, fieldErrors: Record<string, string>): void {
  if (fieldErrors[field]) {
    delete fieldErrors[field]
  }
}

/**
 * 滚动到指定字段
 */
export function scrollToField(
  fieldName: string,
  refs: {
    titleFieldRef?: Ref<HTMLElement | null>
    statusFieldRef?: Ref<HTMLElement | null>
    projectIdFieldRef?: Ref<HTMLElement | null>
    reporterIdFieldRef?: Ref<HTMLElement | null>
  }
): void {
  nextTick(() => {
    let element: HTMLElement | null = null
    
    if (fieldName === 'title' && refs.titleFieldRef?.value) {
      element = refs.titleFieldRef.value
      if (element) {
        const input = element.querySelector('input') as HTMLElement
        if (input) {
          element.scrollIntoView({ behavior: 'smooth', block: 'center' })
          setTimeout(() => input.focus(), 300)
        }
      }
    } else if (fieldName === 'status' && refs.statusFieldRef?.value) {
      element = refs.statusFieldRef.value
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' })
        const select = element.querySelector('.el-select') as HTMLElement
        if (select) {
          setTimeout(() => select.click(), 300)
        }
      }
    } else if (fieldName === 'project_id' && refs.projectIdFieldRef?.value) {
      element = refs.projectIdFieldRef.value
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' })
        const select = element.querySelector('.el-select') as HTMLElement
        if (select) {
          setTimeout(() => select.click(), 300)
        }
      }
    } else if (fieldName === 'reporter_id' && refs.reporterIdFieldRef?.value) {
      element = refs.reporterIdFieldRef.value
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' })
        const select = element.querySelector('.el-select') as HTMLElement
        if (select) {
          setTimeout(() => select.click(), 300)
        }
      }
    }
  })
}

/**
 * 验证必填字段
 */
export function validateRequiredField(
  field: string,
  value: any,
  fieldErrors: Record<string, string>,
  refs: {
    titleFieldRef?: Ref<HTMLElement | null>
    statusFieldRef?: Ref<HTMLElement | null>
    projectIdFieldRef?: Ref<HTMLElement | null>
    reporterIdFieldRef?: Ref<HTMLElement | null>
  }
): boolean {
  clearFieldError(field, fieldErrors)
  
  if (field === 'title') {
    if (!value || (typeof value === 'string' && !value.trim())) {
      fieldErrors.title = '请填写需求标题'
      scrollToField('title', refs)
      return false
    }
  } else if (field === 'project_id') {
    if (!value || value === '') {
      fieldErrors.project_id = '请选择所属项目'
      scrollToField('project_id', refs)
      return false
    }
  } else if (field === 'reporter_id') {
    if (!value || value === '') {
      fieldErrors.reporter_id = '请选择报告人'
      scrollToField('reporter_id', refs)
      return false
    }
  } else if (field === 'status') {
    if (!value || value === '') {
      fieldErrors.status = '请选择状态'
      scrollToField('status', refs)
      return false
    }
  }
  
  return true
}

